package cn.edu.nju.gitlab.presenter;


import cn.edu.nju.gitlab.data.StudentData;
import cn.edu.nju.gitlab.model.Analysis;
import cn.edu.nju.gitlab.activity.AnalysisActivity;
import rx.Subscription;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by lpt on 2017/6/14.
 */

public class AnalysisPresenter{
    private StudentData repository;
    private AnalysisActivity view;
    private Subscription subscription;

    public void getAnalysis(String username, String password, int userId, int assignmentId) {
        subscription = repository.getAnalysis(username, password, userId, assignmentId)
                .subscribeOn(Schedulers.io())
                .onErrorReturn(new Func1<Throwable, Analysis>() {
                    @Override
                    public Analysis call(Throwable throwable) {
                        throwable.printStackTrace();
                        view.showError();
                        return null;
                    }
                })
                .subscribe(new Action1<Analysis>() {
                    @Override
                    public void call(Analysis groups) {
                        if (groups != null) {
                            view.showList(groups.getQuestionResults());
                        }
                    }
                });
    }

    public AnalysisPresenter(StudentData repository, AnalysisActivity view) {
        this.repository = repository;
        this.view = view;
    }


    public void onStop() {
        if (subscription != null && !subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }


    }
